"""
杜伊斯堡签证预约平台 - Flask后端服务
"""
import os
import sys
import uuid
import hashlib
import threading
from datetime import datetime, timedelta
from typing import Dict, Any, Optional

from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
import json
from functools import wraps

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from services.main_service import MainService
from config.settings import SERVICES, EMAIL_CONFIG
from utils.mail import MailSender
from utils.logger import logger

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 全局变量存储待确认的请求
pending_requests = {}
confirmed_requests = {}



# 邮件发送器
mail_sender = MailSender()

# 管理员认证相关
ADMIN_PASSWORD_FILE = 'admin_password.txt'

def get_admin_password():
    """获取管理员密码"""
    if os.path.exists(ADMIN_PASSWORD_FILE):
        with open(ADMIN_PASSWORD_FILE, 'r') as f:
            return f.read().strip()
    else:
        # 生成随机密码
        import secrets
        import string
        password = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(12))
        with open(ADMIN_PASSWORD_FILE, 'w') as f:
            f.write(password)
        logger.log(f"管理员密码已生成: {password}", "admin")
        return password

def verify_admin_auth():
    """验证管理员认证"""
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return False
    
    token = auth_header[7:]  # 移除 'Bearer ' 前缀
    admin_password = get_admin_password()
    return token == admin_password

def require_admin_auth(f):
    """管理员认证装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not verify_admin_auth():
            return jsonify({
                'success': False,
                'error': '需要管理员权限'
            }), 401
        return f(*args, **kwargs)
    return decorated_function

@app.route('/api/services', methods=['GET'])
def get_services():
    """获取可用的服务列表"""
    try:
        services_list = []
        for service_name, service_info in SERVICES.items():
            services_list.append({
                'name': service_name,
                'service_id': service_info['service_id'],
                'duration': service_info['duration'],
                'description': service_info['text']
            })
        
        return jsonify({
            'success': True,
            'data': services_list
        })
    except Exception as e:
        logger.log(f"获取服务列表失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/register', methods=['POST'])
def register_user():
    """用户注册和业务申请"""
    try:
        data = request.get_json()
        
        # 验证必需字段
        required_fields = ['anrede', 'first_name', 'last_name', 'email', 'birthday', 'service']
        for field in required_fields:
            if not data.get(field):
                return jsonify({
                    'success': False,
                    'error': f'缺少必需字段: {field}'
                }), 400
        
        # 生成请求ID
        request_id = str(uuid.uuid4())
        
        # 构建用户信息
        user_info = [
            data['anrede'],      # 称呼
            data['first_name'],  # 名字
            data['last_name'],   # 姓氏
            data.get('address', ''),  # 地址（可选）
            data.get('zip_code', ''), # 邮编（可选）
            data['email'],       # 邮箱
            data['birthday'],    # 生日
            data.get('phone', '') # 电话（可选）
        ]
        
        # 存储待确认的请求
        pending_requests[request_id] = {
            'user_info': user_info,
            'service': data['service'],
            'date_range': data.get('dateRange'),  # 用户指定的时间范围
            'timestamp': datetime.now(),
            'status': 'pending'
        }
        
        # 生成管理员确认链接（使用固定的管理员token）
        admin_token = hashlib.md5(f"admin_{request_id}".encode()).hexdigest()
        # 使用正确的URL构建方式，避免路径重复
        base_url = request.url_root.rstrip('/')
        # 确保base_url不包含api路径
        if base_url.endswith('/api'):
            base_url = base_url[:-4]
        elif base_url.endswith('/api/register'):
            base_url = base_url[:-13]
        confirmation_url = f"{base_url}/api/admin/confirm/{request_id}/{admin_token}"
        rejection_url = f"{base_url}/api/admin/reject/{request_id}/{admin_token}"
        
        # 发送确认邮件（使用翻译友好的模板）
        from utils.mail_translation_friendly import TranslationFriendlyMailSender
        translation_friendly_sender = TranslationFriendlyMailSender()
        success = translation_friendly_sender.send_translation_friendly_confirmation(
            to_addr=EMAIL_CONFIG['to_addr'],
            user_data=data,
            confirmation_url=confirmation_url,
            rejection_url=rejection_url
        )
        
        if success:
            return jsonify({
                'success': True,
                'message': '申请已提交，管理员将收到确认邮件，请耐心等待处理结果',
                'request_id': request_id
            })
        else:
            return jsonify({
                'success': False,
                'error': '邮件发送失败，请稍后重试'
            }), 500
            
    except Exception as e:
        logger.log(f"用户注册失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/admin/confirm/<request_id>/<token>', methods=['GET'])
def admin_confirm_request(request_id: str, token: str):
    """管理员确认用户请求"""
    try:
        if request_id not in pending_requests:
            return render_template_string("""
            <html>
            <head><title>确认失败</title></head>
            <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
                <h1 style="color: #e74c3c;">确认失败</h1>
                <p>请求不存在或已过期</p>
            </body>
            </html>
            """)
        
        request_data = pending_requests[request_id]
        user_info = request_data['user_info']
        
        # 验证管理员token
        expected_token = hashlib.md5(f"admin_{request_id}".encode()).hexdigest()
        if token != expected_token:
            return render_template_string("""
            <html>
            <head><title>确认失败</title></head>
            <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
                <h1 style="color: #e74c3c;">确认失败</h1>
                <p>无效的确认链接</p>
            </body>
            </html>
            """)
        
        # 检查是否过期（24小时）
        if datetime.now() - request_data['timestamp'] > timedelta(hours=24):
            del pending_requests[request_id]
            return render_template_string("""
            <html>
            <head><title>确认失败</title></head>
            <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
                <h1 style="color: #e74c3c;">确认失败</h1>
                <p>确认链接已过期，请重新申请</p>
            </body>
            </html>
            """)
        
        # 确认成功，移动到已确认列表
        confirmed_requests[request_id] = request_data
        confirmed_requests[request_id]['status'] = 'confirmed'
        confirmed_requests[request_id]['confirmed_at'] = datetime.now()
        confirmed_requests[request_id]['user_id'] = request_id  # 添加user_id用于日志关联
        
        del pending_requests[request_id]
        
        # 启动预约流程，传递时间范围
        start_appointment_process(request_id, user_info, request_data['service'], request_data.get('date_range'))
        
        return render_template_string("""
        <html>
        <head><title>确认成功</title></head>
        <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
            <h1 style="color: #27ae60;">确认成功</h1>
            <p>申请已确认，系统正在为用户处理预约...</p>
            <p>用户将收到预约结果通知。</p>
        </body>
        </html>
        """)
        
    except Exception as e:
        logger.log(f"管理员确认请求失败: {e}", "api")
        return render_template_string("""
        <html>
        <head><title>确认失败</title></head>
        <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
            <h1 style="color: #e74c3c;">确认失败</h1>
            <p>系统错误，请稍后重试</p>
        </body>
        </html>
        """)

@app.route('/api/admin/reject/<request_id>/<token>', methods=['GET'])
def admin_reject_request(request_id: str, token: str):
    """管理员拒绝用户请求"""
    try:
        # 检查请求是否在pending中
        if request_id not in pending_requests:
            return render_template_string("""
            <html>
            <head><title>拒绝失败</title></head>
            <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
                <h1 style="color: #e74c3c;">拒绝失败</h1>
                <p>请求不存在或已被处理</p>
            </body>
            </html>
            """)
        
        request_data = pending_requests[request_id]
        user_info = request_data['user_info']
        
        # 验证管理员token
        expected_token = hashlib.md5(f"admin_{request_id}".encode()).hexdigest()
        if token != expected_token:
            return render_template_string("""
            <html>
            <head><title>拒绝失败</title></head>
            <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
                <h1 style="color: #e74c3c;">拒绝失败</h1>
                <p>无效的拒绝链接</p>
            </body>
            </html>
            """)
        
        # 更新状态为拒绝
        confirmed_requests[request_id] = request_data
        confirmed_requests[request_id]['status'] = 'rejected'
        confirmed_requests[request_id]['rejected_at'] = datetime.now()
        del pending_requests[request_id]
        
        # 发送拒绝邮件给用户
        from utils.mail_translation_friendly import TranslationFriendlyMailSender
        translation_friendly_sender = TranslationFriendlyMailSender()
        success = translation_friendly_sender.send_rejection_notification(
            to_addr=user_info[5],  # 发送给用户邮箱
            user_data={
                'anrede': user_info[0],
                'first_name': user_info[1],
                'last_name': user_info[2],
                'email': user_info[5],
                'service': request_data['service']
            }
        )
        
        if success:
            logger.log(f"拒绝邮件发送成功: {request_id}", "api")
        else:
            logger.log(f"拒绝邮件发送失败: {request_id}", "api")
        
        return render_template_string("""
        <html>
        <head><title>申请已拒绝</title></head>
        <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
            <h1 style="color: #e74c3c;">申请已拒绝</h1>
            <p>申请已被拒绝，相关通知已发送给用户。</p>
        </body>
        </html>
        """)
        
    except Exception as e:
        logger.log(f"管理员拒绝请求失败: {e}", "api")
        return render_template_string("""
        <html>
        <head><title>拒绝失败</title></head>
        <body style="font-family: Arial, sans-serif; text-align: center; margin-top: 100px;">
            <h1 style="color: #e74c3c;">拒绝失败</h1>
            <p>系统错误，请稍后重试</p>
        </body>
        </html>
        """)

@app.route('/api/status/<request_id>', methods=['GET'])
def get_request_status(request_id: str):
    """获取请求状态"""
    try:
        if request_id in confirmed_requests:
            request_data = confirmed_requests[request_id]
            status = request_data.get('status', 'confirmed')
            
            # 根据状态返回不同的状态信息
            if status == 'rejected':
                status_info = {
                    'status': 'rejected',
                    'status_text': '已被驳回',
                    'status_color': '#dc3545',  # 红色
                    'data': request_data
                }
            elif status == 'completed':
                status_info = {
                    'status': 'completed',
                    'status_text': f"已成功预约({request_data.get('appointment_date', '')})",
                    'status_color': '#28a745',  # 绿色
                    'data': request_data
                }
            elif status == 'paused':
                status_info = {
                    'status': 'paused',
                    'status_text': '已暂停',
                    'status_color': '#ffc107',  # 黄色
                    'data': request_data
                }
            else:  # confirmed, processing
                status_info = {
                    'status': 'processing',
                    'status_text': '已确认，处理中',
                    'status_color': '#28a745',  # 绿色
                    'data': request_data
                }
            
            return jsonify({
                'success': True,
                **status_info
            })
        elif request_id in pending_requests:
            return jsonify({
                'success': True,
                'status': 'pending',
                'status_text': '等待审批确认',
                'status_color': '#6c757d',  # 灰色
                'data': pending_requests[request_id]
            })
        else:
            return jsonify({
                'success': False,
                'error': '请求不存在'
            }), 404
            
    except Exception as e:
        logger.log(f"获取状态失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


def start_appointment_process(request_id: str, user_info: list, service_name: str, date_range: list = None):
    """启动预约流程"""
    def run_appointment():
        try:
            logger.log(f"开始处理用户预约请求: {request_id}", "appointment")
            
            # 创建主服务实例
            main_service = MainService(user_id=request_id)
            
            # 临时创建候选人配置
            temp_candidate_name = f"temp_{request_id}"
            temp_candidate = {
                'info': user_info,
                'service': service_name
            }
            
            # 将临时候选人添加到配置中
            from config.candidates import CANDIDATES
            CANDIDATES[temp_candidate_name] = temp_candidate
            
            # 运行预约流程，传递时间范围
            success = main_service.run_candidate(temp_candidate_name, date_range)
            
            # 清理临时候选人
            if temp_candidate_name in CANDIDATES:
                del CANDIDATES[temp_candidate_name]
            
            # 更新状态
            if request_id in confirmed_requests:
                confirmed_requests[request_id]['status'] = 'completed' if success else 'failed'
                confirmed_requests[request_id]['completed_at'] = datetime.now()
                confirmed_requests[request_id]['result'] = success
            
            logger.log(f"预约流程完成: {request_id}, 结果: {success}", "appointment")
            
        except Exception as e:
            logger.log(f"预约流程异常: {request_id}, 错误: {e}", "appointment")
            if request_id in confirmed_requests:
                confirmed_requests[request_id]['status'] = 'error'
                confirmed_requests[request_id]['error'] = str(e)
    
    # 在新线程中运行预约流程
    thread = threading.Thread(target=run_appointment)
    thread.daemon = True
    thread.start()

@app.route('/api/queue/status', methods=['GET'])
@require_admin_auth
def get_queue_status():
    """获取队列状态"""
    try:
        from user_queue_manager import UserQueueManager
        
        manager = UserQueueManager()
        manager.load_requests(pending_requests, confirmed_requests)
        
        status = manager.get_queue_status()
        return jsonify({
            'success': True,
            'data': status
        })
    except Exception as e:
        logger.log(f"获取队列状态失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/queue/pending', methods=['GET'])
@require_admin_auth
def get_pending_users():
    """获取待确认用户列表"""
    try:
        from user_queue_manager import UserQueueManager
        
        manager = UserQueueManager()
        manager.load_requests(pending_requests, confirmed_requests)
        
        users = manager.get_pending_users()
        return jsonify({
            'success': True,
            'data': users
        })
    except Exception as e:
        logger.log(f"获取待确认用户失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/queue/confirmed', methods=['GET'])
@require_admin_auth
def get_confirmed_users():
    """获取已确认用户列表"""
    try:
        from user_queue_manager import UserQueueManager
        
        manager = UserQueueManager()
        manager.load_requests(pending_requests, confirmed_requests)
        
        users = manager.get_confirmed_users()
        return jsonify({
            'success': True,
            'data': users
        })
    except Exception as e:
        logger.log(f"获取已确认用户失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/queue/user/<request_id>', methods=['GET'])
@require_admin_auth
def get_user_details(request_id: str):
    """获取用户详细信息"""
    try:
        from user_queue_manager import UserQueueManager
        
        manager = UserQueueManager()
        manager.load_requests(pending_requests, confirmed_requests)
        
        user_details = manager.get_user_details(request_id)
        if user_details:
            return jsonify({
                'success': True,
                'data': user_details
            })
        else:
            return jsonify({
                'success': False,
                'error': '用户不存在'
            }), 404
    except Exception as e:
        logger.log(f"获取用户详情失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/queue/user/<request_id>', methods=['DELETE'])
@require_admin_auth
def remove_user(request_id: str):
    """移除用户（取消申请）"""
    try:
        from user_queue_manager import UserQueueManager
        
        manager = UserQueueManager()
        manager.load_requests(pending_requests, confirmed_requests)
        
        success = manager.remove_user(request_id)
        if success:
            # 同步到全局变量
            if request_id in pending_requests:
                del pending_requests[request_id]
            elif request_id in confirmed_requests:
                del confirmed_requests[request_id]
            
            return jsonify({
                'success': True,
                'message': '用户已移除'
            })
        else:
            return jsonify({
                'success': False,
                'error': '用户不存在'
            }), 404
    except Exception as e:
        logger.log(f"移除用户失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/queue/statistics', methods=['GET'])
@require_admin_auth
def get_queue_statistics():
    """获取队列统计信息"""
    try:
        from user_queue_manager import UserQueueManager
        
        manager = UserQueueManager()
        manager.load_requests(pending_requests, confirmed_requests)
        
        stats = manager.get_statistics()
        return jsonify({
            'success': True,
            'data': stats
        })
    except Exception as e:
        logger.log(f"获取队列统计失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/queue/cleanup', methods=['POST'])
@require_admin_auth
def cleanup_expired_requests():
    """清理过期的请求"""
    try:
        from user_queue_manager import UserQueueManager
        
        manager = UserQueueManager()
        manager.load_requests(pending_requests, confirmed_requests)
        
        # 获取清理参数
        hours = request.json.get('hours', 24) if request.json else 24
        cleaned_count = manager.cleanup_expired_requests(hours)
        
        # 同步到全局变量
        expired_requests = manager.get_expired_requests(hours)
        for request_id in expired_requests:
            if request_id in pending_requests:
                del pending_requests[request_id]
        
        return jsonify({
            'success': True,
            'message': f'已清理 {cleaned_count} 个过期请求',
            'cleaned_count': cleaned_count
        })
    except Exception as e:
        logger.log(f"清理过期请求失败: {e}", "api")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/admin/auth', methods=['POST'])
def admin_auth():
    """管理员认证接口"""
    try:
        data = request.get_json()
        password = data.get('password', '') if data else ''
        
        admin_password = get_admin_password()
        if password == admin_password:
            return jsonify({
                'success': True,
                'token': admin_password,
                'message': '认证成功'
            })
        else:
            return jsonify({
                'success': False,
                'error': '密码错误'
            }), 401
    except Exception as e:
        logger.log(f"管理员认证失败: {e}", "admin")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/admin/current-password', methods=['GET'])
def get_current_admin_password():
    """获取当前管理员密码（用于前端显示）"""
    try:
        admin_password = get_admin_password()
        return jsonify({
            'success': True,
            'password': admin_password
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/admin/regenerate', methods=['POST'])
@require_admin_auth
def regenerate_admin_password():
    """重新生成管理员密码"""
    try:
        # 删除现有密码文件
        if os.path.exists(ADMIN_PASSWORD_FILE):
            os.remove(ADMIN_PASSWORD_FILE)
        
        # 生成新密码
        new_password = get_admin_password()
        
        logger.log(f"管理员密码已重新生成: {new_password}", "admin")
        
        return jsonify({
            'success': True,
            'message': '密码已重新生成',
            'new_password': new_password
        })
    except Exception as e:
        logger.log(f"重新生成管理员密码失败: {e}", "admin")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500






@app.route('/api/dashboard/data', methods=['GET'])
@require_admin_auth
def get_dashboard_data():
    """获取仪表板数据"""
    try:
        # 计算时间范围
        now = datetime.now()
        today = now.date()
        week_ago = today - timedelta(days=7)
        month_ago = today - timedelta(days=30)
        
        # 统计数据
        total_requests = len(pending_requests) + len(confirmed_requests)
        pending_count = len(pending_requests)
        confirmed_count = len(confirmed_requests)
        
        # 按状态统计
        status_stats = {
            'pending': pending_count,
            'confirmed': len([r for r in confirmed_requests.values() if r.get('status') == 'confirmed']),
            'processing': len([r for r in confirmed_requests.values() if r.get('status') == 'processing']),
            'completed': len([r for r in confirmed_requests.values() if r.get('status') == 'completed']),
            'failed': len([r for r in confirmed_requests.values() if r.get('status') == 'failed']),
            'error': len([r for r in confirmed_requests.values() if r.get('status') == 'error'])
        }
        
        # 按服务类型统计
        service_stats = {}
        for request in list(pending_requests.values()) + list(confirmed_requests.values()):
            service = request.get('service', '未知服务')
            service_stats[service] = service_stats.get(service, 0) + 1
        
        # 按日期统计（最近7天）
        daily_stats = {}
        for i in range(7):
            date = (today - timedelta(days=i)).strftime('%Y-%m-%d')
            daily_stats[date] = 0
        
        # 统计每日请求数
        for request in list(pending_requests.values()) + list(confirmed_requests.values()):
            request_date = request.get('timestamp', now).date()
            if request_date >= week_ago:
                date_str = request_date.strftime('%Y-%m-%d')
                if date_str in daily_stats:
                    daily_stats[date_str] += 1
        
        # 成功率统计
        total_processed = status_stats['completed'] + status_stats['failed'] + status_stats['error']
        success_rate = (status_stats['completed'] / total_processed * 100) if total_processed > 0 else 0
        
        return jsonify({
            'success': True,
            'data': {
                'overview': {
                    'total_requests': total_requests,
                    'pending_count': pending_count,
                    'confirmed_count': confirmed_count,
                    'success_rate': round(success_rate, 2)
                },
                'status_distribution': status_stats,
                'service_distribution': service_stats,
                'daily_trend': daily_stats,
                'last_updated': now.isoformat()
            }
        })
    except Exception as e:
        logger.log(f"获取仪表板数据失败: {e}", "admin")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/logs/<request_id>', methods=['GET'])
@require_admin_auth
def get_user_logs(request_id: str):
    """获取用户日志"""
    try:
        # 尝试从confirmed_requests中获取用户信息
        user_info = None
        if request_id in confirmed_requests:
            user_info = confirmed_requests[request_id]['user_info']
        elif request_id in pending_requests:
            user_info = pending_requests[request_id]['user_info']
        
        # 构建日志文件路径
        if user_info:
            # 使用"姓_名"格式
            first_name = user_info[1]
            last_name = user_info[2]
            log_filename = f"{last_name}_{first_name}"
            log_file_path = f"/app/logs/logs-{log_filename}"
        else:
            # 回退到使用request_id
            log_file_path = f"/app/logs/logs-{request_id}"
        
        # 记录调试信息
        logger.log(f"尝试获取日志: request_id={request_id}, log_file_path={log_file_path}", "admin")
        
        # 检查日志文件是否存在
        if not os.path.exists(log_file_path):
            logger.log(f"日志文件不存在: {log_file_path}", "admin")
            return jsonify({
                'success': True,
                'logs': [],
                'message': '暂无日志记录'
            })
        
        # 读取日志文件
        logs = []
        try:
            with open(log_file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line:
                        logs.append(line)
            logger.log(f"成功读取日志文件: {log_file_path}, 共{len(logs)}行", "admin")
        except Exception as e:
            logger.log(f"读取日志文件失败: {e}", "admin")
            return jsonify({
                'success': False,
                'error': '读取日志文件失败'
            }), 500
        
        # 取最后100行，然后倒序（最新的在前）
        recent_logs = logs[-100:][::-1]
        
        return jsonify({
            'success': True,
            'logs': recent_logs,
            'total_count': len(logs)
        })
        
    except Exception as e:
        logger.log(f"获取用户日志失败: {e}", "admin")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        'success': True,
        'message': '服务运行正常',
        'timestamp': datetime.now().isoformat()
    })

if __name__ == '__main__':
    logger.log("杜伊斯堡签证预约平台后端服务启动", "system")
    app.run(host='0.0.0.0', port=5000, debug=True)


